import fs from 'fs';
import { merge } from 'lodash';
import path from 'path';
import { parse } from 'yaml';

// 获取项目运行环境
export const getEnv = () => {
  return process.env.RUNNING_ENV;
};

export const isDev = getEnv() === 'dev';
export const isTest = getEnv() === 'test';
export const isPro = getEnv() === 'pro';

type ConfigType =
  | 'FEISHU_CONFIG'
  | 'KEY'
  | 'DB_CONFIG'
  | 'REDIS_CONFIG'
  | 'DD'
  | 'NEST'
  | 'ATM';

interface EnvConfig {
  DD: {
    DD_AppKey: string;
    DD_AppSecret: string;
    DD_MiniAppId: string;
    DD_CorpId: string;
    DD_AgentId: string;
  };

  DB_CONFIG: {
    type: 'mysql' | 'mariadb';
    host: string;
    port: number;
    username: string;
    password: string;
    database: string;
    retryDelay: number;
    retryAttempts: number;
    synchronize: boolean;
    autoLoadEntities: boolean;
  };

  REDIS_CONFIG: {
    host: string;
    password: string;
    port: number;
    db: number;
  };

  NEST: {
    port: number;
  };

  JWT: {
    secret: string;
    access_token_expires_time: string;
    refresh_token_expires_time: string;
  };

  USER_MICROSERVICES: { host: string; port: number };

  LOG: {
    enable: boolean;
    level: string;
  };
}

const commonConfig = (): EnvConfig => {
  const p = path.join(process.cwd(), `./.config/.common.yaml`);
  const file = fs.readFileSync(p, 'utf8');
  const config = parse(file);
  return config;
};

let envConfig = {} as EnvConfig;

// 读取项目配置
export const getConfig = (type?: ConfigType): EnvConfig => {
  if (!Object.keys(envConfig).length) {
    const environment = getEnv() || 'dev';
    const p = path.join(process.cwd(), `./.config/.${environment}.yaml`);
    const file = fs.readFileSync(p, 'utf8');
    const config = parse(file);

    const common = commonConfig();
    envConfig = merge(common, config);
  }

  if (type) {
    return envConfig[type];
  }

  return envConfig;
};
